<?php

$wx = new Wx();

class Wx {

    const token = 'chenyanmu123';

    public function __construct() {
        if (!empty($_GET['echostr'])) {
            $this->checkSign();
        }
        else {
            $this->sendMsg();
        }
    }

    //第一次验证
    private function checkSign() {
        $token     = self::token;
        $timestamp = $_GET['timestamp'];
        $nonce     = $_GET['nonce'];
        $signature = $_GET['signature'];
        $tmpArr    = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);

        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($signature == $tmpStr) {
            echo $_GET['echostr'];
        }
        else {
            return false;
        }
    }

    private function sendMsg() {
        $xml     = file_get_contents('php://input');
        # 把xml转换为object对象来处理
        $obj     = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        //接收信息写入日志
        $this->writeLog($xml);
        //判断接受类型
        $msgType = $obj->MsgType;
        //进入相应类型方法
        $fun = $msgType."Fun";
        $ret = $this->$fun($obj);
        //输出，回复信息
        echo $ret;
        //回复信息写入日志
        $this->writeLog($ret,2);
    }
    
    private function textFun($obj) {
        $content = $obj->Content;
        if($content == '音乐'){
            return $this->musicFun($obj);
        }
        $content = "公总号：".$content;
        return $this->createText($obj,$content);
    }
    
    private function imageFun($obj) {
        $mediaId = 'XtohOne-M4R4xJOm_biDt74P0DmIDQ6sc1hyibN9yGtDcsILkIfsV6dw3byxu-Lp';
        return $this->createImage($obj,$mediaId);
    }
    
    private function musicFun($obj) {
        $mediaId = 'd9h1rutn4FbQZhkiQkBvBTUGC7amk8tQSjF2jzFkOSfviLFn2orQOyg3mRWP8ooP';
        $url = 'https://wx.1314000.cn/mp3/ykz.mp3';
        return $this->createMusic($obj,$url,$mediaId);
    }
    private function voiceFun($obj) {
        $mediaId = $obj->MediaId;
        return $this->createVoice($obj,$mediaId);
    }
    
    private function eventFun($obj) {
        $event = $obj->Event;
        switch ($event) {
            case 'CLICK':
                return $this->clickFun($obj);//点击事件
                break;
        }
    }
    private function clickFun($obj) {
        $EventKey = $obj->EventKey;
        if($EventKey == 'key00') return $this->musicFun ($obj);
    }

    private function createText($obj,$content) {
        $str = '<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
          </xml>';
        return sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),$content);
    }
    
    private function createImage($obj,$mediaId) {
        $str = '<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            <Image>
              <MediaId><![CDATA[%s]]></MediaId>
            </Image>
          </xml>';
        return sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),$mediaId);
    }
    
    private function createMusic($obj,$url,$mediaId) {
        $str = '<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[music]]></MsgType>
            <Music>
              <Title><![CDATA[夜空中最亮的星]]></Title>
              <Description><![CDATA[一首很好听的歌]]></Description>
              <MusicUrl><![CDATA[%s]]></MusicUrl>
              <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
              <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
            </Music>
          </xml>';
        return sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),$url,$url,$mediaId);
    }
    
    private function createVoice($obj,$mediaId) {
        
        $str = '<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[voice]]></MsgType>
        <Voice>
          <MediaId><![CDATA[%s]]></MediaId>
        </Voice>
      </xml>';
        return sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),$mediaId);
    }


    private function writeLog($data, $type = 1) {
        $str  = '';
        $type = $type == 1 ? "接受" : "发送";
        $str .= "【{$type}】" . date('Y-m-d') . "--------------------------------------------------\n";
        $str .= $data . "\n--------------------------------------------------\n";
        file_put_contents("log/wx.xml", $str, FILE_APPEND);
        return true;
    }

}
